package Offer;
//输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。

import org.junit.Test;

import java.util.Stack;

/*
    思路：借助栈的先进后出，实现逆序存储（输出）
* */
public class T06_reversePrint {
    @Test
    public void test() {
        int[] vals = {1, 3, 2};
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        head.next = node1;
        node1.next = node2;

        reversePrint(head);

    }

//    法2 自定义栈
    public int[] reversePrint2(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        int size = 0;
        while (head != null) {
            stack.push(head);
            head = head.next;
            size++;
        }

        int[] vals = new int[size];
        int index = 0;
        while (!stack.isEmpty()) {
            ListNode node = stack.pop();
            vals[index] = node.val;
            index++;
        }
        return vals;
    }

    //    法1 递归
    public int[] reversePrint(ListNode head) {
        ListNode p = head;
        int size=0;
        while (p != null) {
            p = p.next;
            size++;
        }
//        System.out.println(size);

        int[] vals = new int[size];
        reverse(head, vals, size - 1);
        return vals;
    }
    void reverse(ListNode head, int[] vals, int index) {
        if (head == null) {
            return;
        }
        reverse(head.next, vals, index-1);
        vals[index] = head.val;
    }
}


class ListNode {
    int val;        //默认值为0
    ListNode next;  //默认值为null
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}